class DataUtils::Processing::Aliases < DataUtils::Processing::Processor
    def self.process(params)
        params.each do |k,v|
            params[k] = lookup(k, v)
        end
        return params
    end
    def self.add(type, aka, original)
        add_table(type) unless table_exists?(type)
        if(alias_exists?(type, aka))
            update(type, aka, original)
        else
            DataUtils.db.execute("INSERT INTO #{type}_aliases(alias, original) VALUES(:aka, :original)", {:aka => aka, :original => original})
        end
    end
    def self.remove(type, aka)
        DataUtils.db.execute("DELETE FROM #{type}_aliases WHERE alias = ?", aka)
    end
    def self.reset(type)
        DataUtils.db.execute("DELETE FROM #{type}_aliases")
    end
    private
    def self.lookup(type, aka)
        return aka unless table_exists?(type)
        return get_alias(type, aka) || aka
    end
    def self.get_alias(type, aka)
        orig =  DataUtils.db.execute("SELECT original FROM #{type}_aliases WHERE alias = ?", aka)
        return orig.empty? ? nil : orig[0][0]
    end
    def self.update(type, aka, original)
        DataUtils.db.execute("UPDATE #{type}_aliases SET original = :original WHERE alias = :aka", {:aka => aka, :original => original})
    end
    def self.add_table(type)
        template = ERB.new(File.read(DataUtils.db_dir + "templates/aliases"))
        DataUtils.db.execute(template.result(binding()))
    end
    def self.alias_exists?(type, aka)
        return !DataUtils.db.execute("SELECT * FROM #{type}_aliases WHERE alias = ?", aka).empty?
    end
    def self.table_exists?(type)
        return !DataUtils.db.execute("SELECT * FROM sqlite_master WHERE type = 'table' AND name = '#{type}_aliases'").empty?
    end
    def self.method_missing(method_id, *arguments)
        intention = method_id.to_s.split('_')
        method = intention[0].to_sym
        type = intention[1].to_sym
        self.send(method, type,*arguments)
    end
end
